﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Mimoza.ObjectLayer;

namespace Mimoza.ServiceLayer
{
    public class ServiceHostController : BaseObject
    {
        public ServiceHostController(Configuration config)
            : base(config)
        {
        }

        override public void Init()
        {
            Configuration.ObjectLayer.HostRepository.OnObjectChanged += OnHostChanged;
        }

        override public void Shutdown()
        {
            Configuration.ObjectLayer.HostRepository.OnObjectChanged -= OnHostChanged;
        }

        void OnHostChanged(object sender, Mimoza.ObjectLayer.ObjectLayer_ObjectChangedEventArgs eventArg)
        {
            if (!(eventArg.Object is Mimoza.ObjectLayer.Host))
            {
                Common.Logger.Log.Error("ServiceHostController.OnHostChanged ERROR Object is not host.");
                return;
            }

            if (eventArg.EventType == ObjectLayerEventType.ObjectDeleted) return;

            Mimoza.ObjectLayer.Host modifiedHost = eventArg.Object as Mimoza.ObjectLayer.Host;

            if (modifiedHost == null || modifiedHost.Record == null)
            {
                Common.Logger.Log.Error("ServiceHostController.OnHostChanged ERROR Host is empty.");
                return;
            }

            if (NotificationInfo.IsSet())
            {
                Common.Logger.Log.Info("ServiceHostController.OnHostChanged NotificationInfo.Get is not empty  - LastConnectionTime modified.");
                return;
            }

            Common.Logger.Log.Info("ServiceHostController.OnHostChanged operation - '" + eventArg.EventType.ToString() +
                "' id - '" + modifiedHost.ID.ToString() + "' Name - '" + modifiedHost.Name + "'.");

            Configuration.HostsConnectionInitiator.AddHost(modifiedHost);
        }

    }
}
